package com.anxinr.controller.common;

import com.anxinr.exception.LogicException;
import com.anxinr.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * 公共的服务层
 * @author anxinr
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value(value = "${server.port}")
    public String basePort ;
    public static final String LOCALHOST = "http://localhost" ;
    public static final String BASE_FILE_PATH = "/images/" ;

    /**
     * 上传文件  img
     * @return Result
     */
    @PostMapping("/updateFile")
    public Result<String> updateFile(@RequestPart  MultipartFile file) throws IOException {
        if (Objects.isNull(file)){
            throw new LogicException("上传文件不能为空!") ;
        }
        /**项目存储静态资源地址*/
        String path = new File(ResourceUtils.getURL("classpath:static/images/").getPath()).getAbsolutePath() + "\\" ;
        /**uuid 文件名*/
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        /**项目对外访问静态资源地址*/
        String url = LOCALHOST + ":" + basePort + BASE_FILE_PATH + fileName ;
        File serverFile = new File(path + fileName);
        /**创建文件夹*/
        if (!serverFile.exists()) {
            boolean mkdirs = serverFile.getParentFile().mkdirs();
            System.out.println("mkdirs = " + mkdirs);
        }
        serverFile.createNewFile() ;
        file.transferTo(serverFile);
        return new Result<String>(url);
    }
}
